package controllers

import (
	"github.com/huichen/wukong/engine"
	"github.com/huichen/wukong/types"
	"findme-api/models"
)

var (
	Searcher = engine.Engine{}
	docId    uint64
)

//加载数据，建立索引,searchty为不同表中的类别，searchlittletype为同一表中的不同类别
func loadIndex(username string,searchtype string,searchlittletype string){
	searchChan := make(chan string, 100000)
	if searchtype == "label"{
		models.SearchLabel(searchChan,username,searchlittletype)
	}else if searchtype == "alarm" {
		models.SearchAlarm(searchChan,username,searchlittletype)
	}
    var i int = 0
	var lenlabelchan = len(searchChan)
	for item := range searchChan{
		//fmt.Println("get labeldata from database:",item)
		docId++
		//fmt.Println(docId)
		//建立索引
		Searcher.IndexDocument(docId, types.DocumentIndexData{Content: item}, true)
		if i == (lenlabelchan - 1) {
			break
		}
		i++
	}
	//将索引号清零
	docId = 0
}


//返回搜索词在搜索索引中的位置
func Search(message string,slice *[]uint64,username string,searchtype string,searchlittletype string) {
	loadIndex(username,searchtype,searchlittletype)
	Searcher.FlushIndex()
    //fmt.Println("======刷新索引成功=======")
	//fmt.Printf("%#v\n", Searcher.Search(types.SearchRequest{Text: message}))
	//搜索
	seaResult := Searcher.Search(types.SearchRequest{Text: message})
	for _,item := range seaResult.Docs {
		//fmt.Println("DocId is :",item.DocId)
		*slice = append(*slice, item.DocId)
	}
	//return "ss"
}

